﻿using System;
using System.Net;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security.Permissions;
using System.Web;

namespace ConsoleTest
{
    /// <summary>
    /// This class implements the API for posting blog to LiveJournal
    /// </summary>
    public sealed class HexunMicroblogging
    {
        private CookieCollection cookies;
        private CookieContainer cookieContainer;

        private string userDefaultPage = string.Empty;

        public HexunMicroblogging()
        {
            cookies = new CookieCollection();
            cookieContainer = new CookieContainer();
        }

        public bool LoginFromDefaultPage(string username, string password)
        {
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;

                // Username and password.
                username = HttpUtility.UrlEncode(username);
                password = HttpUtility.UrlEncode(password);

                // Login uri and referrer uri.
                string loginUri = "http://reg.hexun.com/login.aspx?gourl=http://t.hexun.com/home.html";
                //loginUri += "&username=" + username + "&password=" + password;
                
                string loginReferUri = "http://t.hexun.com/rest/indexlogin.aspx";

                // Prepare the HttpWebRequest to send data to t.hexun.com
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUri);
                request.Method = "POST";

                //request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2";
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB7.1";
                request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                request.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
                request.KeepAlive = true;
                request.Referer = loginReferUri;
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookieContainer;
                //request.AllowAutoRedirect = false;
                string postData = string.Format("username={0}&password={1}", username, password);
                byte[] postBuffer = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(postData);
                //byte[] postBuffer = System.Text.Encoding.GetEncoding("gb2312").GetBytes(postData);
                //byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
                //byte[] postBuffer = System.Text.Encoding.ASCII.GetBytes(postData); // error?
                request.ContentLength = postBuffer.Length;
                Stream postDataStream = request.GetRequestStream();
                postDataStream.Write(postBuffer, 0, postBuffer.Length);
                postDataStream.Close();

                CookieCollection requestCookies1 = request.CookieContainer.GetCookies(request.RequestUri);
                Console.WriteLine("Start of request cookies 1");
                foreach (Cookie c in requestCookies1)
                {
                    Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                }
                Console.WriteLine("End of request cookies 1");

                // Get response.
                string responseHtml = string.Empty;
                System.Net.WebResponse webResponse = request.GetResponse();
                System.Net.HttpWebResponse httpWebResponse = webResponse as System.Net.HttpWebResponse;

                Stream responseStream = webResponse.GetResponseStream();
                Encoding encoding = System.Text.Encoding.GetEncoding(httpWebResponse.CharacterSet);
                using (StreamReader reader = new StreamReader(responseStream, encoding, true))
                {
                    HttpStatusCode responseStatusCode = httpWebResponse.StatusCode;

                    CookieCollection requestCookies2 = request.CookieContainer.GetCookies(request.RequestUri);
                    Console.WriteLine("Start of request cookies 2");
                    foreach (Cookie c in requestCookies2)
                    {
                        Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                    }
                    Console.WriteLine("End of request cookies 2");

                    /*
                    CookieCollection responseCookies = httpWebResponse.Cookies;
                    Console.WriteLine("Start of response cookies");
                    foreach (Cookie c in responseCookies)
                    {
                        Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                    }
                    Console.WriteLine("End of response cookies");
                    */

                    httpWebResponse.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

                    // Add the cookie to this instance of object, such that the cookies can be reused for next request.
                    cookies.Add(httpWebResponse.Cookies);

                    Uri responseUri = webResponse.ResponseUri;
                    string requestUri = loginUri;
                    string responseLocation = webResponse.Headers["Location"]; // Location:  /dennis_zsc/default.html
                    string cookieHeader1 = request.CookieContainer.GetCookieHeader(new Uri(loginUri));
                    string cookieHeader2 = request.CookieContainer.GetCookieHeader(responseUri);
                    string cookieHeader3 = webResponse.Headers["Set-Cookie"];
                    bool areTwoHeadersEquals = cookieHeader1.Equals(cookieHeader2);

                    responseHtml = reader.ReadToEnd();

                    string homeUri = "http://t.hexun.com/home.htm";
                    if (responseUri.ToString().ToLower().Contains(homeUri))
                    {
                        System.Threading.Thread.Sleep(2000);
                        return LoginFromDefaultPage(username, password);
                    }

                    userDefaultPage = responseUri.ToString();
                    return LoginFromSpecifiedPage(userDefaultPage, username, password);
                }

                return true;
            }
            catch (Exception ex)
            {
                this.cookieContainer = null;
                this.cookies = null;
                Console.WriteLine(ex.Message);
            }

            return false;
        }

        public bool LoginFromSpecifiedPage(string uri, string username, string password)
        {
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;

                // Username and password.
                username = HttpUtility.UrlEncode(username);
                password = HttpUtility.UrlEncode(password);

                // Login uri and referrer uri.
                string loginUri = uri;
                loginUri += "?username=" + username + "&password=" + password;

                string loginReferUri = "http://t.hexun.com/rest/indexlogin.aspx";

                // Prepare the HttpWebRequest to send data to t.hexun.com
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(loginUri);
                request.Method = "POST";

                //request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2";
                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB7.1";
                request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
                request.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
                request.KeepAlive = true;
                request.Referer = loginReferUri;
                request.ContentType = "application/x-www-form-urlencoded";
                request.CookieContainer = cookieContainer;
                //request.AllowAutoRedirect = false;
                string postData = string.Format("username={0}&password={1}", username, password);
                byte[] postBuffer = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(postData);
                //byte[] postBuffer = System.Text.Encoding.GetEncoding("gb2312").GetBytes(postData);
                //byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
                //byte[] postBuffer = System.Text.Encoding.ASCII.GetBytes(postData); // error?
                request.ContentLength = postBuffer.Length;
                Stream postDataStream = request.GetRequestStream();
                postDataStream.Write(postBuffer, 0, postBuffer.Length);
                postDataStream.Close();

                CookieCollection requestCookies1 = request.CookieContainer.GetCookies(request.RequestUri);
                Console.WriteLine("Start of request cookies 1");
                foreach (Cookie c in requestCookies1)
                {
                    Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                }
                Console.WriteLine("End of request cookies 1");

                // Get response.
                string responseHtml = string.Empty;
                System.Net.WebResponse webResponse = request.GetResponse();
                System.Net.HttpWebResponse httpWebResponse = webResponse as System.Net.HttpWebResponse;

                Stream responseStream = webResponse.GetResponseStream();
                Encoding encoding = System.Text.Encoding.GetEncoding(httpWebResponse.CharacterSet);
                using (StreamReader reader = new StreamReader(responseStream, encoding, true))
                {
                    HttpStatusCode responseStatusCode = httpWebResponse.StatusCode;

                    CookieCollection requestCookies2 = request.CookieContainer.GetCookies(request.RequestUri);
                    Console.WriteLine("Start of request cookies 2");
                    foreach (Cookie c in requestCookies2)
                    {
                        Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                    }
                    Console.WriteLine("End of request cookies 2");

                    /*
                    CookieCollection responseCookies = httpWebResponse.Cookies;
                    Console.WriteLine("Start of response cookies");
                    foreach (Cookie c in responseCookies)
                    {
                        Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                    }
                    Console.WriteLine("End of response cookies");
                    */

                    httpWebResponse.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

                    // Add the cookie to this instance of object, such that the cookies can be reused for next request.
                    cookies.Add(httpWebResponse.Cookies);

                    Uri responseUri = webResponse.ResponseUri;
                    //Uri httpResponseUri = httpWebResponse.ResponseUri;

                    string requestUri = loginUri;
                    string responseLocation = webResponse.Headers["Location"]; // Location:  /dennis_zsc/default.html
                    string cookieHeader1 = request.CookieContainer.GetCookieHeader(new Uri(loginUri));
                    string cookieHeader2 = request.CookieContainer.GetCookieHeader(responseUri);
                    //string cookieHeader3 = webResponse.Headers["Set-Cookie"];
                    //bool areTwoHeadersEquals = cookieHeader1.Equals(cookieHeader2);

                    responseHtml = reader.ReadToEnd();
                }

                return true;
            }
            catch (Exception ex)
            {
                this.cookieContainer = null;
                this.cookies = null;
                Console.WriteLine(ex.Message);
            }

            return false;
        }
        
        //public bool LoginFromLoginPage(string username, string password)
        //{
        //    try
        //    {
        //        username = HttpUtility.UrlEncode(username);
        //        password = HttpUtility.UrlEncode(password);

        //        string loginUir = "http://reg.hexun.com/login.aspx?gourl=http://t.hexun.com/home.html";
        //        //string loginUir = "http://reg.hexun.com/login.aspx?gourl=http://t.hexun.com/home.html&username=" + username + "&password" + password;
        //        string loginReferUri = "http://t.hexun.com/rest/indexlogin.aspx";

        //        // Prepare the HttpWebRequest to send data to LiveJournal.com
        //        string url = loginUir;
        //        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        //        request.Method = "POST";

        //        //request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7) Gecko/20040707 Firefox/0.9.2";
        //        request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB7.1";
        //        request.Accept = "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
        //        request.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5");
        //        request.Headers.Add("Accept-Encoding", "gzip,deflate");
        //        request.Headers.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");

        //        request.KeepAlive = true;
        //        request.Referer = loginReferUri;
        //        request.ContentType = "application/x-www-form-urlencoded";
        //        request.CookieContainer = cookieContainer;
        //        //request.AllowAutoRedirect = false;

        //        // Send the log-in data
        //        //string postData = string.Format("TextBoxUserName={0}&TextBoxPassword={1}", HttpUtility.UrlEncode(username), HttpUtility.UrlEncode(password));
        //        //string postData = string.Format("&TextBoxUserName={0}&TextBoxPassword={1}", username, password);
        //        //postData += "&Submit=";
        //        //postData += "&submitsign=1";
        //        //postData += "&hiddenReferrer=http://t.hexun.com/default.htm";
        //        //postData += "&TextGpic=";
        //        //postData += "&gourl=http://t.hexun.com/home.html";
        //        //postData += "&timestamp=" + DateTime.Now.Ticks;


        //        string postData = string.Format("username={0}&password={1}", username, password);

        //        byte[] postBuffer = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(postData);
        //        //byte[] postBuffer = System.Text.Encoding.GetEncoding("gb2312").GetBytes(postData);
        //        //byte[] postBuffer = System.Text.Encoding.GetEncoding(1252).GetBytes(postData);
        //        //byte[] postBuffer = System.Text.Encoding.ASCII.GetBytes(postData); // error?

        //        request.ContentLength = postBuffer.Length;
        //        Stream postDataStream = request.GetRequestStream();
        //        postDataStream.Write(postBuffer, 0, postBuffer.Length);
        //        postDataStream.Close();

        //        string responseHtml = "";


        //        //// Get resopose.
        //        //System.Net.WebResponse response = request.GetResponse();

        //        //string m_cookieheader = request.CookieContainer.GetCookieHeader(new Uri(url));
        //        //string cookieWebHeaders = response.Headers["Set-Cookie"];

        //        //Stream receiveStream = response.GetResponseStream();
        //        //using (StreamReader reader = new StreamReader(receiveStream, System.Text.Encoding.GetEncoding("GB2312")))
        //        //{
        //        //    responseHtml = reader.ReadToEnd();
        //        //    Console.WriteLine(responseHtml);
        //        //}


        //        // Get the response
        //        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //        HttpStatusCode responseStatusCode = response.StatusCode;
        //        string requestUri = loginUir;
        //        string responseLocation = response.Headers["Location"]; // Location:  /dennis_zsc/default.html
        //        string responseUri = response.ResponseUri.ToString();
        //        string cookieHeader1 = request.CookieContainer.GetCookieHeader(new Uri(url));
        //        string cookieHeader2 = request.CookieContainer.GetCookieHeader(response.ResponseUri);
        //        bool twoHeadersEquals = cookieHeader1.Equals(cookieHeader2);
        //        string cookieHeader3 = response.Headers["Set-Cookie"];
        //        response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

        //        // Add the cookie to this instance of object, such that the cookies can be reused
        //        // for next request
        //        Cookies.Add(response.Cookies);

        //        // Read the response from the stream
        //        Encoding enc = System.Text.Encoding.GetEncoding(response.CharacterSet);
        //        StreamReader responseStream = new StreamReader(response.GetResponseStream(), enc, true);

        //        responseHtml = responseStream.ReadToEnd();
        //        response.Close();
        //        responseStream.Close();

        //        // For debug purpose, print out the cookies received from LiveJournal.com
        //        foreach (Cookie c in response.Cookies)
        //        {
        //            Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
        //        }

        //        Console.Write(responseHtml);
        //        return true;
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine(ex.Message);
        //        return false;
        //    }
        //}

        public bool IssueViaWebBrowser()
        {
            System.Windows.Forms.WebBrowser wb = new System.Windows.Forms.WebBrowser();
            wb.Navigate(userDefaultPage);

            string issueUri = "http://t.hexun.com/wbresponse.aspx";
            string issueReferUri = userDefaultPage;
            string content = "中文编码测试" + Guid.NewGuid().ToString();
            content = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
            issueUri += "?content=" + System.Web.HttpUtility.UrlEncode(content);
            issueUri += "&fromUserID=0";
            issueUri += "&fromUserName= ";
            issueUri += "&fromArticleContent= ";
            issueUri += "&RssUrl= ";
            issueUri += "&RssTitle= ";
            issueUri += "&PhotoID=0";
            issueUri += "&QuoteStockCode= ";
            issueUri += "&QuoteStockPhotoID=0";
            issueUri += "&isActiveUser=1";
            issueUri += "&pubWeiBoFlag=1";
            issueUri += "&videoHtml= ";
            issueUri += "&videoTitle= ";
            issueUri += "&videoPic= ";
            issueUri += "&voteId= ";
            issueUri += "&VoteInfo=";

            wb.Navigate(issueUri);

            return false;
        }

        public bool IssueMicrobloggingText()
        {
            try
            {
                System.Net.ServicePointManager.Expect100Continue = false;

                // URI and data for post.
                string issueUri = "http://t.hexun.com/wbresponse.aspx";
                string issueReferUri = userDefaultPage;
                string content = "中文编码测试" +Guid.NewGuid().ToString();
                content = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";
                issueUri += "?content=" + System.Web.HttpUtility.UrlEncode(content);
                issueUri += "&fromUserID=0";
                issueUri += "&fromUserName= ";
                issueUri += "&fromArticleContent= ";
                issueUri += "&RssUrl= ";
                issueUri += "&RssTitle= ";
                issueUri += "&PhotoID=0";
                issueUri += "&QuoteStockCode= ";
                issueUri += "&QuoteStockPhotoID=0";
                issueUri += "&isActiveUser=1";
                issueUri += "&pubWeiBoFlag=1";
                issueUri += "&videoHtml= ";
                issueUri += "&videoTitle= ";
                issueUri += "&videoPic= ";
                issueUri += "&voteId= ";
                issueUri += "&VoteInfo=";
                
                // Prepare the HttpWebRequest to send data to t.hexun.com
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(issueUri);
                request.Method = "GET";

                request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.1.7) Gecko/20091221 Firefox/3.5.7 GTB7.1";
                request.Accept = "Accept:  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers.Add("Accept-Language", "zh-cn,zh;q=0.5");
                request.Headers.Add("Accept-Encoding", "gzip,deflate");
                request.Headers.Add("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
                request.KeepAlive = true;
                request.Referer = issueReferUri;
                request.CookieContainer = cookieContainer;

                CookieCollection requestCookies1 = request.CookieContainer.GetCookies(request.RequestUri);
                /*
                Console.WriteLine("Start of request cookies 3");
                foreach (Cookie c in requestCookies1)
                {
                    Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                }
                Console.WriteLine("End of request cookies 3");
                */

                // Get response.
                string responseHtml = string.Empty;
                Encoding enc = Encoding.UTF8;
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response != null)
                    {
                        if (response.StatusCode == HttpStatusCode.OK && request.HaveResponse)
                        {
                            using (StreamReader sr = new StreamReader(response.GetResponseStream(), enc, true))
                            {
                                if (sr != null)
                                {
                                    responseHtml = sr.ReadToEnd();
                                }
                            }
                        }
                        response.Close();
                    }
                }

                /*
                System.Net.WebResponse webResponse = request.GetResponse();
                System.Net.HttpWebResponse httpWebResponse = webResponse as System.Net.HttpWebResponse;

                Stream responseStream = webResponse.GetResponseStream();
                //Encoding encoding = System.Text.Encoding.GetEncoding(httpWebResponse.CharacterSet);
                Encoding encoding = System.Text.Encoding.UTF8;
                using (StreamReader reader = new StreamReader(responseStream, encoding))
                {
                    HttpStatusCode responseStatusCode = httpWebResponse.StatusCode;

                    CookieCollection requestCookies2 = request.CookieContainer.GetCookies(request.RequestUri);
                    Console.WriteLine("Start of request cookies 4");
                    foreach (Cookie c in requestCookies2)
                    {
                        Console.WriteLine(string.Format("{0}: {1}", c.Name, c.Value));
                    }
                    Console.WriteLine("End of request cookies 4");

                    httpWebResponse.Cookies = request.CookieContainer.GetCookies(request.RequestUri);

                    // Add the cookie to this instance of object, such that the cookies can be reused for next request.
                    cookies.Add(httpWebResponse.Cookies);

                    Uri responseUri = webResponse.ResponseUri;
                    string requestUri = issueUrl;
                    string responseLocation = webResponse.Headers["Location"]; // Location:  /dennis_zsc/default.html
                    string cookieHeader1 = request.CookieContainer.GetCookieHeader(new Uri(issueUrl));
                    string cookieHeader2 = request.CookieContainer.GetCookieHeader(responseUri);
                    string cookieHeader3 = webResponse.Headers["Set-Cookie"];
                    bool areTwoHeadersEquals = cookieHeader1.Equals(cookieHeader2);

                    responseHtml = reader.ReadToEnd();
                }
                */

                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return false;
            }
        }
    }
}
